package com.example.vue_shop.components.shop.controller;

import com.example.vue_shop.components.shop.entity.Shop;
import com.example.vue_shop.components.shop.entity.ShopVo;
import com.example.vue_shop.components.shop.service.ShopService;
import com.example.vue_shop.utils.ResultN;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lipengwei
 */
@RestController
@RequestMapping("shop")
@Api(tags = "商品管理")
public class ShopController {

    @Resource(name = "shopServiceImpl")
    private ShopService shopService;

    /**
     * 获取商品列表.
     * @param query 查询条件
     * @param pageNum 页数
     * @param pageSize 每页显示的数量
     * @return String
     */
    @ApiOperation(value = "获取商品列表", notes = "获取商品列表。")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "query", value = "查询条件", dataType =
                    "string"),
            @ApiImplicitParam(name = "pageNum", value = "页数", dataType =
                    "int", defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize", value = "每页显示的数量", dataType
                    = "int", defaultValue = "5")
    })
    @GetMapping("/getShopList")
    public String getShopList(
            @RequestParam(required = false) String query,
            @RequestParam(required = false,defaultValue = "1") int pageNum,
            @RequestParam(required = false,defaultValue = "5") int pageSize) {
        try{
            Map<String, Object> resultMap = shopService.getShopList(query, pageNum, pageSize);
            return ResultN.success(resultMap, "获取商品列表成功！");
        }catch (Exception e) {
            e.printStackTrace();
            return ResultN.error("获取商品列表失败！");
        }
    }

    /**
     * 删除商品.
     * @param id 商品Id
     * @return String
     */
    @ApiOperation(value = "删除商品", notes = "删除商品。")
    @DeleteMapping("/delShop")
    public String delShop(int id) {
        try {
            shopService.delShop(id);
            return ResultN.success("删除商品成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultN.error("删除商品失败！");
        }
    }

    /**
     * 新增商品.
     * @param shop 商品对象
     * @return String
     */
    @ApiOperation(value = "新增商品", notes = "新增商品。")
    @PostMapping("/addShop")
    public String addShop(@RequestBody ShopVo shopVo) {
        try {
            // 商品，商品图片list新增 ，商品参数 更新
            shopService.addShop(shopVo);
            return ResultN.success("新增商品成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultN.error("新增商品失败！");
        }
    }

    /**
     * 上传图片
     * @return String
     */
    @ApiOperation(value = "上传图片", notes = "上传图片。。。")
    @PostMapping("/uploadImage")
    public String uploadImage(HttpServletRequest request, @RequestParam(
            "file") MultipartFile image) {
        try {
            //2.根据时间戳创建新的文件名，这样即便是第二次上传相同名称的文件，也不会把第一次的文件覆盖了
            String fileName = System.currentTimeMillis() + image.getOriginalFilename();
            //3.通过req.getServletContext().getRealPath("") 获取当前项目的真实路径，然后拼接前面的文件名
            // 绝对路径
            String destFileName =
                    request.getServletContext().getRealPath("") + "uploaded" + File.separator + fileName;

            String baseUrl = "http://" + request.getLocalAddr() + ":" + request
                    .getLocalPort() + "/";

            String serverPath =
                    baseUrl  + "uploaded" + File.separator + fileName;

            //4.第一次运行的时候，这个文件所在的目录往往是不存在的，这里需要创建一下目录（创建到了webapp下uploaded文件夹下）
            File destFile = new File(destFileName);
            destFile.getParentFile().mkdirs();
            //5.把浏览器上传的文件复制到希望的位置
            image.transferTo(destFile);
            Map<String, Object> result = new HashMap<>(1);
            result.put("path", serverPath);
            return ResultN.success(result, "上传图片成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultN.error("上传图片失败！");
        }

    }

}
